package com.eduagent.xwqeduagent.api.imageTranslation.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;

/**
 * 权限工具类
 */
@Slf4j
public class AuthUtils {

    /**
     * 生成权限字符串
     *
     * @param params 参数Map
     * @param apiKey API密钥
     * @param appId 应用ID
     * @return 包含认证参数的Map
     */
    public static TreeMap<String, Object> generateAuthParams(TreeMap<String, Object> params, String apiKey, String appId) {
        if (params == null) {
            params = new TreeMap<>();
        }
        
        // 添加appId和时间戳
        params.put("appId", appId);
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        
        // 构建参数字符串
        StringBuilder paramStrBuilder = new StringBuilder("apikey=" + apiKey);
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            
            // 跳过空值和特殊字段
            if (value == null || "".equals(value) || "authStr".equals(key) || "file".equals(key) || "base64".equals(key)) {
                continue;
            }
            
            paramStrBuilder.append("&").append(key).append("=").append(value);
        }
        
        String paramStr = paramStrBuilder.toString();
        
        // 使用MD5加密参数字符串
        String authStr = DigestUtils.md5DigestAsHex(paramStr.getBytes(StandardCharsets.UTF_8));
        params.put("authStr", authStr);
        
        log.debug("Auth params generated: {}", params);
        return params;
    }
} 